//
//  ForgetPassWordTableViewController.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/7/25.
//  Copyright © 2018年 四川中农. All rights reserved.
//

import UIKit

// 忘记密码

class ForgetPassWordTableViewController: BaseTableViewController {
    
    @IBOutlet weak var phoneField: UITextField!
    @IBOutlet weak var verificationCodeField: UITextField!
    @IBOutlet weak var passWordField: UITextField!
    @IBOutlet weak var confirmField: UITextField!
    @IBOutlet weak var sendCodeBtn: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
        self.title = "忘记密码"
        
        
        self.phoneField.addTarget(self, action: #selector(valueChange(textField:)), for: .editingChanged)
        self.verificationCodeField.addTarget(self, action: #selector(valueChange(textField:)), for: .editingChanged)
        self.passWordField.addTarget(self, action: #selector(valueChange(textField:)), for: .editingChanged)
        self.confirmField.addTarget(self, action: #selector(valueChange(textField:)), for: .editingChanged)
        
        self.phoneField.setValue(UIColor.init(hexColor: "#cccccc"), forKeyPath: "_placeholderLabel.textColor")
        self.verificationCodeField.setValue(UIColor.init(hexColor: "#cccccc"), forKeyPath: "_placeholderLabel.textColor")
        self.passWordField.setValue(UIColor.init(hexColor: "#cccccc"), forKeyPath: "_placeholderLabel.textColor")
        self.confirmField.setValue(UIColor.init(hexColor: "#cccccc"), forKeyPath: "_placeholderLabel.textColor")
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    // MARK:确定
    @IBAction func confirmBtnClick(_ sender: UIButton) {
        
//        if self.phoneField.text?.count == 0 {
//            self.noticeOnlyText("请输入手机号")
//            return
//        }
        if self.phoneField.text?.count != 11  {
            PKhud.showText(text: "请输入正确的手机号~")
            self.phoneField.becomeFirstResponder()
            return
        }
        
        if self.verificationCodeField.text?.count != 4 {
            PKhud.showText(text: "请输入正确的验证码~")
            self.verificationCodeField.becomeFirstResponder()
            return
        }
        
        if (self.passWordField.text?.count)! < 6 {
            PKhud.showText(text: "密码强度过低，需至少6位~")
            self.passWordField.becomeFirstResponder()
            return
        }
        
        if self.passWordField.text != self.confirmField.text {
            PKhud.showText(text: "两次密码不一致，请重新填写~")
            self.confirmField.becomeFirstResponder()
            return
        }
        
        PKhud.show()
        let parameter:postParameters = ["username":self.phoneField.text!,"password":self.passWordField.text!,"code":self.verificationCodeField.text!]
        HttpRequest.requestData(.post, URLString: Api.reset_password.rawValue, parameters: parameter) { (result) in
            PKhud.hiden()
            if result["msg"] as! String == "success"{
                PKhud.showText(text: result["data"] as! String)
                Utils.DispatchAfter(after: 2, handler: {
                    self.backBarButtonMethon()
                })
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    // MARK:发送验证码
    @IBAction func sendVerificationCode(_ sender: UIButton) {
        HttpRequest.requestData(.post, URLString: Api.get_code.rawValue, parameters: ["username":self.phoneField.text!,"type":1]) { (result) in
            if result["msg"] as! String == "success"{
                self.dispatchTimer(timeInterval: 1, handler: { (count) in
                    sender.setTitle("剩余"+"‘\(count)s", for: .normal)
                    sender.isUserInteractionEnabled = false
                })
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    func dispatchTimer(timeInterval: Double, handler:@escaping (Int)->()){
        var timeCount = 61
        let codeTimer = DispatchSource.makeTimerSource(queue:DispatchQueue.global())
        codeTimer.schedule(deadline: .now(), repeating: timeInterval)
        codeTimer.setEventHandler(handler: {
            
            timeCount = timeCount - 1
            
            if timeCount <= 0 {
                codeTimer.cancel()
            }
            
            DispatchQueue.main.async {
                if timeCount <= 0 {
                    self.sendCodeBtn.isUserInteractionEnabled = true
                    self.sendCodeBtn.setTitle("获取验证码", for: .normal)
                }else{
                    handler(timeCount)
                }
                
            }
        })
        codeTimer.resume()
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return 4
    }
    
    @objc func valueChange(textField:UITextField){
        var maxLength = 0
        if textField == self.phoneField {
            maxLength = 11
        }else if textField == self.verificationCodeField{
            maxLength = 4
        }else{
            maxLength = 12
        }
        let toBeString = textField.text!
        let lang = textField.textInputMode?.primaryLanguage
        if lang == "zh-Hans" {
            let selectedRange = textField.markedTextRange
            if selectedRange == nil && toBeString.count > maxLength{
                let endIndex = toBeString.index(toBeString.startIndex, offsetBy: maxLength)
                textField.text = String(toBeString[..<endIndex])
            }
        }else if toBeString.count > maxLength {
            let endIndex = toBeString.index(toBeString.startIndex, offsetBy: maxLength)
            textField.text = String(toBeString[..<endIndex])
        }
    }

}
